#!/bin/bash

# ============================================
# Web3管理平台 - 超级一键部署脚本 v3.0
# ============================================

set -e

# 颜色和图标
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly BLUE='\033[0;34m'
readonly PURPLE='\033[0;35m'
readonly CYAN='\033[0;36m'
readonly NC='\033[0m'

readonly ROCKET="🚀"
readonly CHECK="✅"
readonly CROSS="❌"
readonly WARN="⚠️"
readonly INFO="💡"
readonly GEAR="⚙️"

# 项目信息
readonly PROJECT_NAME="Web3管理平台"
readonly VERSION="3.0.0"
readonly GITHUB_REPO="your-repo-url" # 替换为实际仓库地址

# 自动检测系统信息
detect_system() {
    OS=$(uname -s | tr '[:upper:]' '[:lower:]')
    ARCH=$(uname -m)

    case $ARCH in
        x86_64) ARCH="amd64" ;;
        arm64|aarch64) ARCH="arm64" ;;
        *) echo "${CROSS} 不支持的架构: $ARCH"; exit 1 ;;
    esac

    # 检测系统类型
    if [[ -f /etc/os-release ]]; then
        . /etc/os-release
        DISTRO=$ID
        DISTRO_VERSION=$VERSION_ID
    else
        DISTRO="unknown"
    fi

    # 检测可用内存
    if command -v free &> /dev/null; then
        MEMORY_GB=$(free -g | awk '/^Mem:/{print $2}')
    else
        MEMORY_GB=4 # 默认假设4GB
    fi
}

# 美化输出函数
print_header() {
    echo -e "${PURPLE}"
    echo "╔══════════════════════════════════════════════════════════╗"
    echo "║                    ${PROJECT_NAME}                    ║"
    echo "║                   超级一键部署 v${VERSION}                   ║"
    echo "╚══════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
}

print_section() {
    echo ""
    echo -e "${CYAN}▶ $1${NC}"
    echo "─────────────────────────────────────────────────────────"
}

log_success() { echo -e "${GREEN}${CHECK} $1${NC}"; }
log_error() { echo -e "${RED}${CROSS} $1${NC}"; }
log_warn() { echo -e "${YELLOW}${WARN} $1${NC}"; }
log_info() { echo -e "${BLUE}${INFO} $1${NC}"; }
log_step() { echo -e "${CYAN}${GEAR} $1${NC}"; }

# 智能环境检测和配置
auto_configure() {
    print_section "智能环境检测"

    detect_system

    log_info "系统信息: $DISTRO $DISTRO_VERSION ($OS/$ARCH)"
    log_info "可用内存: ${MEMORY_GB}GB"

    # 智能配置Docker资源限制
    if [[ $MEMORY_GB -lt 2 ]]; then
        log_warn "内存不足2GB，使用最小配置"
        JAVA_OPTS="-Xms256m -Xmx512m"
        MYSQL_BUFFER="128M"
    elif [[ $MEMORY_GB -lt 4 ]]; then
        log_info "内存2-4GB，使用标准配置"
        JAVA_OPTS="-Xms512m -Xmx1024m"
        MYSQL_BUFFER="256M"
    else
        log_success "内存充足，使用高性能配置"
        JAVA_OPTS="-Xms1024m -Xmx2048m"
        MYSQL_BUFFER="512M"
    fi

    # 检测可用端口
    check_ports=(80 443 8080 3306 6379)
    for port in "${check_ports[@]}"; do
        if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1; then
            log_warn "端口 $port 已被占用，将自动调整"
            case $port in
                80) FRONTEND_PORT=8081 ;;
                443) FRONTEND_SSL_PORT=8444 ;;
                8080) BACKEND_PORT=8081 ;;
                3306) MYSQL_PORT=3307 ;;
                6379) REDIS_PORT=6380 ;;
            esac
        fi
    done
}

# 一键安装Docker
install_docker() {
    if command -v docker &> /dev/null; then
        log_success "Docker已安装"
        return
    fi

    print_section "安装Docker环境"

    case $DISTRO in
        ubuntu|debian)
            log_step "安装Docker (Ubuntu/Debian)..."
            curl -fsSL https://get.docker.com -o get-docker.sh
            sudo sh get-docker.sh
            sudo usermod -aG docker $USER
            ;;
        centos|rhel)
            log_step "安装Docker (CentOS/RHEL)..."
            sudo yum install -y yum-utils
            sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
            sudo yum install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
            sudo systemctl start docker
            sudo systemctl enable docker
            sudo usermod -aG docker $USER
            ;;
        *)
            log_error "不支持的操作系统，请手动安装Docker"
            exit 1
            ;;
    esac

    log_success "Docker安装完成"
}

# 智能生成配置
generate_smart_config() {
    print_section "生成智能配置"

    # 生成强密码
    MYSQL_ROOT_PASS=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-25)
    MYSQL_USER_PASS=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-25)
    JWT_SECRET=$(openssl rand -base64 64 | tr -d "=+/" | cut -c1-50)

    # 自动配置环境变量
    cat > .env << EOF
# ============================================
# Web3管理平台 - 自动生成配置
# 生成时间: $(date)
# ============================================

# 数据库配置
MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASS
MYSQL_USER=web3user
MYSQL_PASSWORD=$MYSQL_USER_PASS

# JWT配置
JWT_SECRET=$JWT_SECRET
JWT_EXPIRATION=86400

# 应用配置
LOG_LEVEL=INFO
SHOW_SQL=false

# 端口配置
FRONTEND_PORT=${FRONTEND_PORT:-80}
FRONTEND_SSL_PORT=${FRONTEND_SSL_PORT:-443}
BACKEND_PORT=${BACKEND_PORT:-8080}

# 性能配置
JAVA_OPTS=$JAVA_OPTS
MYSQL_BUFFER=$MYSQL_BUFFER

# 时区配置
TZ=Asia/Shanghai
EOF

    log_success "配置文件已自动生成"
    log_info "数据库密码已自动生成并加密保存"
}

# 增强的健康检查
enhanced_health_check() {
    print_section "系统健康检查"

    local services=("mysql" "redis" "backend" "frontend")
    local all_healthy=true

    echo ""
    printf "%-12s %-8s %-15s %-20s\n" "服务" "状态" "健康检查" "响应时间"
    echo "────────────────────────────────────────────────────────"

    for service in "${services[@]}"; do
        local container="web3-$service"
        local status="运行中"
        local health="健康"
        local response_time="N/A"

        # 检查容器状态
        if ! docker ps --format "table {{.Names}}" | grep -q "$container"; then
            status="${RED}已停止${NC}"
            health="${RED}失败${NC}"
            all_healthy=false
        else
            # 健康检查
            case $service in
                "mysql")
                    if docker exec $container mysqladmin ping -h localhost --silent 2>/dev/null; then
                        health="${GREEN}健康${NC}"
                        response_time=$(docker exec $container mysqladmin ping -h localhost 2>/dev/null | grep -o '[0-9]*\.[0-9]*' | head -1)ms
                    else
                        health="${RED}异常${NC}"
                        all_healthy=false
                    fi
                    ;;
                "redis")
                    if docker exec $container redis-cli ping >/dev/null 2>&1; then
                        health="${GREEN}健康${NC}"
                        response_time="<1ms"
                    else
                        health="${RED}异常${NC}"
                        all_healthy=false
                    fi
                    ;;
                "backend")
                    response=$(curl -s -w "%{time_total},%{http_code}" http://localhost:${BACKEND_PORT:-8080}/actuator/health 2>/dev/null || echo "0,000")
                    time_total=$(echo $response | cut -d',' -f1)
                    http_code=$(echo $response | cut -d',' -f2)
                    if [[ "$http_code" == "200" ]]; then
                        health="${GREEN}健康${NC}"
                        response_time="${time_total}s"
                    else
                        health="${RED}异常${NC}"
                        all_healthy=false
                    fi
                    ;;
                "frontend")
                    response=$(curl -s -w "%{time_total},%{http_code}" http://localhost:${FRONTEND_PORT:-80}/ 2>/dev/null || echo "0,000")
                    time_total=$(echo $response | cut -d',' -f1)
                    http_code=$(echo $response | cut -d',' -f2)
                    if [[ "$http_code" == "200" ]]; then
                        health="${GREEN}健康${NC}"
                        response_time="${time_total}s"
                    else
                        health="${RED}异常${NC}"
                        all_healthy=false
                    fi
                    ;;
            esac
        fi

        printf "%-12s %-15s %-25s %-20s\n" "$service" "$status" "$health" "$response_time"
    done

    echo ""
    if [[ "$all_healthy" == true ]]; then
        log_success "所有服务运行正常"
    else
        log_warn "部分服务存在问题，请检查日志"
    fi
}

# 智能部署选择
smart_deploy() {
    print_section "智能部署配置"

    echo "请选择部署模式："
    echo "1) ${GREEN}全自动部署${NC} - 零配置，一键启动 (推荐)"
    echo "2) ${BLUE}自定义部署${NC} - 手动配置参数"
    echo "3) ${YELLOW}升级模式${NC} - 更新现有部署"
    echo "4) ${PURPLE}开发模式${NC} - 包含调试工具"
    echo ""
    read -p "请选择 (1-4): " deploy_choice

    case $deploy_choice in
        1) deploy_mode="auto" ;;
        2) deploy_mode="custom" ;;
        3) deploy_mode="upgrade" ;;
        4) deploy_mode="dev" ;;
        *) log_error "无效选择"; exit 1 ;;
    esac
}

# 全自动部署
auto_deploy() {
    print_section "执行全自动部署"

    # 1. 环境准备
    log_step "准备部署环境..."
    auto_configure
    generate_smart_config

    # 2. 快速构建
    log_step "快速构建镜像..."
    docker-compose build --parallel --quiet

    # 3. 启动服务
    log_step "启动服务..."
    docker-compose up -d

    # 4. 等待就绪
    log_step "等待服务就绪..."
    wait_for_ready

    # 5. 自动初始化
    log_step "执行自动初始化..."
    auto_initialize

    log_success "全自动部署完成！"
}

# 等待服务就绪（带进度条）
wait_for_ready() {
    local services=("mysql:3306" "redis:6379" "backend:8080" "frontend:80")
    local max_wait=120

    for service_port in "${services[@]}"; do
        local service=$(echo $service_port | cut -d':' -f1)
        local port=$(echo $service_port | cut -d':' -f2)

        echo -n "等待 $service 服务启动"

        for ((i=1; i<=max_wait; i++)); do
            if check_service_ready $service $port; then
                echo -e " ${GREEN}${CHECK}${NC}"
                break
            fi
            echo -n "."
            sleep 1

            if [[ $i -eq $max_wait ]]; then
                echo -e " ${RED}${CROSS}${NC}"
                log_error "$service 服务启动超时"
                show_troubleshooting $service
                exit 1
            fi
        done
    done
}

# 检查服务就绪状态
check_service_ready() {
    local service=$1
    local port=$2

    case $service in
        "mysql")
            docker exec web3-mysql mysqladmin ping -h localhost --silent 2>/dev/null
            ;;
        "redis")
            docker exec web3-redis redis-cli ping >/dev/null 2>&1
            ;;
        "backend")
            curl -s http://localhost:$port/actuator/health >/dev/null 2>&1
            ;;
        "frontend")
            curl -s http://localhost:$port/ >/dev/null 2>&1
            ;;
    esac
}

# 自动初始化
auto_initialize() {
    # 执行数据库迁移
    if [[ -f "backend/add_restart_fields.sql" ]]; then
        log_step "执行数据库迁移..."
        docker exec -i web3-mysql mysql -u root -p$MYSQL_ROOT_PASS web3_management < backend/add_restart_fields.sql
        log_success "数据库迁移完成"
    fi

    # 检查管理员账号
    log_step "检查管理员账号..."
    local admin_exists=$(docker exec web3-mysql mysql -u root -p$MYSQL_ROOT_PASS web3_management -e "SELECT COUNT(*) FROM users WHERE username='admin'" 2>/dev/null | tail -1)

    if [[ "$admin_exists" == "0" ]]; then
        log_info "创建默认管理员账号..."
        # 这里可以调用后端API创建管理员账号
    fi
}

# 实时状态面板
show_dashboard() {
    clear
    print_header

    echo -e "${CYAN}📊 实时状态面板${NC}"
    echo ""

    # 显示基本信息
    echo -e "🌐 访问地址: ${BLUE}http://localhost:${FRONTEND_PORT:-80}${NC}"
    echo -e "🔧 API地址:  ${BLUE}http://localhost:${BACKEND_PORT:-8080}${NC}"
    echo -e "👤 默认账号: ${YELLOW}admin / admin123${NC}"
    echo ""

    # 实时健康检查
    enhanced_health_check

    echo ""
    echo -e "${CYAN}📈 系统监控${NC}"
    echo "────────────────────────────────────────────────────────"

    # 显示资源使用情况
    docker stats --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}" $(docker ps --format "{{.Names}}" | grep web3- | tr '\n' ' ')

    echo ""
    echo "按 Ctrl+C 退出监控"
}

# 故障排查指南
show_troubleshooting() {
    local service=$1
    echo ""
    log_error "$service 服务启动失败，故障排查指南："
    echo ""

    case $service in
        "mysql")
            echo "📋 MySQL故障排查："
            echo "1. 检查日志: docker logs web3-mysql"
            echo "2. 检查端口: netstat -tulpn | grep 3306"
            echo "3. 重启服务: docker restart web3-mysql"
            ;;
        "backend")
            echo "📋 后端服务故障排查："
            echo "1. 检查日志: docker logs web3-backend"
            echo "2. 检查配置: docker exec web3-backend env | grep DB_"
            echo "3. 检查连接: docker exec web3-backend curl mysql:3306"
            ;;
        "frontend")
            echo "📋 前端服务故障排查："
            echo "1. 检查日志: docker logs web3-frontend"
            echo "2. 检查Nginx: docker exec web3-frontend nginx -t"
            echo "3. 重启服务: docker restart web3-frontend"
            ;;
    esac
}

# 升级功能
upgrade_system() {
    print_section "系统升级"

    log_step "检查更新..."

    # 备份数据
    log_step "创建备份..."
    local backup_dir="backups/$(date +%Y%m%d_%H%M%S)"
    mkdir -p $backup_dir

    docker exec web3-mysql mysqldump -u root -p$MYSQL_ROOT_PASS web3_management > $backup_dir/database.sql
    cp .env $backup_dir/
    docker cp web3-backend:/app/logs $backup_dir/ 2>/dev/null || true

    log_success "备份完成: $backup_dir"

    # 拉取最新代码
    if [[ -d ".git" ]]; then
        log_step "拉取最新代码..."
        git pull
    else
        log_warn "非Git仓库，请手动更新代码"
    fi

    # 优雅重启
    log_step "执行无缝更新..."
    docker-compose build --quiet
    docker-compose up -d --no-deps backend # 先更新后端
    sleep 10
    docker-compose up -d --no-deps frontend # 再更新前端

    log_success "升级完成"
}

# 主菜单
show_main_menu() {
    clear
    print_header

    echo "请选择操作："
    echo ""
    echo "🚀 部署相关"
    echo "  1) 全自动部署 (推荐)"
    echo "  2) 自定义部署"
    echo "  3) 升级系统"
    echo ""
    echo "📊 管理相关"
    echo "  4) 实时状态面板"
    echo "  5) 查看日志"
    echo "  6) 重启服务"
    echo "  7) 停止服务"
    echo ""
    echo "🔧 工具相关"
    echo "  8) 数据库管理"
    echo "  9) 备份数据"
    echo "  10) 故障诊断"
    echo ""
    echo "  0) 退出"
    echo ""
    read -p "请选择 (0-10): " menu_choice

    case $menu_choice in
        1) auto_deploy; show_dashboard ;;
        2) custom_deploy ;;
        3) upgrade_system ;;
        4) while true; do show_dashboard; sleep 5; done ;;
        5) show_logs_menu ;;
        6) docker-compose restart; log_success "服务重启完成" ;;
        7) docker-compose down; log_success "服务已停止" ;;
        8) database_management ;;
        9) backup_data ;;
        10) system_diagnosis ;;
        0) exit 0 ;;
        *) log_error "无效选择"; sleep 1; show_main_menu ;;
    esac
}

# 数据库管理
database_management() {
    print_section "数据库管理"

    echo "1) 进入数据库命令行"
    echo "2) 执行SQL文件"
    echo "3) 数据库备份"
    echo "4) 数据库恢复"
    echo "5) 查看表结构"
    read -p "请选择: " db_choice

    case $db_choice in
        1) docker exec -it web3-mysql mysql -u root -p$MYSQL_ROOT_PASS web3_management ;;
        2)
            read -p "请输入SQL文件路径: " sql_file
            docker exec -i web3-mysql mysql -u root -p$MYSQL_ROOT_PASS web3_management < $sql_file
            ;;
        3)
            backup_dir="backups/$(date +%Y%m%d_%H%M%S)"
            mkdir -p $backup_dir
            docker exec web3-mysql mysqldump -u root -p$MYSQL_ROOT_PASS web3_management > $backup_dir/database.sql
            log_success "备份完成: $backup_dir/database.sql"
            ;;
        4)
            read -p "请输入备份文件路径: " backup_file
            docker exec -i web3-mysql mysql -u root -p$MYSQL_ROOT_PASS web3_management < $backup_file
            ;;
        5) docker exec web3-mysql mysql -u root -p$MYSQL_ROOT_PASS web3_management -e "SHOW TABLES;" ;;
    esac
}

# 主入口
main() {
    # 检查是否以root运行
    if [[ $EUID -eq 0 ]]; then
        log_warn "不建议以root身份运行，继续执行可能有安全风险"
        read -p "确定继续? (y/N): " confirm
        [[ ! $confirm =~ ^[Yy]$ ]] && exit 1
    fi

    # 解析参数
    case ${1:-""} in
        --install)
            print_header
            install_docker
            exit 0
            ;;
        --upgrade)
            upgrade_system
            exit 0
            ;;
        --status)
            enhanced_health_check
            exit 0
            ;;
        --dashboard)
            while true; do show_dashboard; sleep 5; done
            ;;
        "")
            show_main_menu
            ;;
        *)
            echo "用法: $0 [--install|--upgrade|--status|--dashboard]"
            echo ""
            echo "一键安装: curl -fsSL https://your-domain.com/install.sh | bash"
            exit 1
            ;;
    esac
}

# 启动主程序
main "$@"